package cn.edu.zzu.nlp.utopiar.action;

import java.awt.event.ActionEvent;
import java.util.List;

import javax.swing.JOptionPane;

import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.view.mxGraph;

import cn.edu.zzu.nlp.readTree.SaveTree;
import cn.edu.zzu.nlp.readTree.TreeParser;
import cn.edu.zzu.nlp.utopiar.editor.EditorBottom;
import cn.edu.zzu.nlp.utopiar.editor.EditorTabbedPane;
import cn.edu.zzu.nlp.utopiar.editor.EditorToolBar;
import cn.edu.zzu.nlp.utopiar.editor.GraphEditor;
import cn.edu.zzu.nlp.utopiar.util.SetLabel;

public class ActionSort extends ActionGraph{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void actionPerformed(ActionEvent e) {
		GraphEditor editor = getEditor(e);
		mxGraphComponent graphComponent = GraphEditor.getGraphComponent();
		final mxGraph graph = graphComponent.getGraph();
		Object cell = null;
		try {
			List<Object> list = graph.findTreeRoots(graph.getDefaultParent());
					
			if(list.size()>1){
				String str = "";
				for (int i =0;i<list.size();i++) {
					str=str+graph.getLabel(list.get(i))+"  ";
				}
				JOptionPane.showMessageDialog(editor, "现有"+list.size()+"个根节点："+str);
				return;
			}else {
				for (Object object : list) {
					cell = object;
				}
			}
			graph.selectCells(true, false);
			Object []objects = graph.getSelectionCells();	
			for (Object object : objects) {
				if(objects.length==1)
					break;
				int count = graph.getModel().getEdgeCount(object);				
				if(count<1){
					System.out.println(graph.getLabel(object));
					JOptionPane.showMessageDialog(editor, "结点\""+graph.getLabel(object)+"\"是孤立结点！");
					graph.clearSelection();
					return;
				}
			}
			graph.clearSelection();
			String temp = traverse(cell, graph);
			String[] strings = temp.split(" ");
			for (String string2 : strings) {
				System.out.println(string2);
				if(!string2.contains(")(")&&string2.contains("(")&&!string2.startsWith("(")){
					JOptionPane.showMessageDialog(editor, "请核对叶子结点是否正确！","警告",JOptionPane.WARNING_MESSAGE);
					return ;
				}
			}
			temp = "( " + temp.replaceAll("\\)\\(", "\\) \\(") + " )";
			SaveTree.save(TreeParser.getNow(), temp, EditorTabbedPane.getPATH());
			graph.selectAll();
			graph.removeCells();
			TreeParser.setCountleaf(1);
			List<String> list1 = TreeParser.getWord(TreeParser.getNow(),TreeParser.selectData(EditorTabbedPane.getPATH()));
			TreeParser.getLeaf().clear();
			TreeParser.getSplitList().clear();
			EditorToolBar.getCombobox().setSelectedIndex(0);
			TreeParser.creatTree(editor,graphComponent,list1,  0);
			EditorBottom.getTextArea().setText(SetLabel.setLabel());
		} catch (Exception e1) {
			e1.printStackTrace();
	    }		
	}

}
